import json, pickle, base64

from django.shortcuts import render
from django import http
from django.views.generic import View
from django.core.exceptions import ObjectDoesNotExist
from django_redis import get_redis_connection
from django.conf import settings

from goods.models import SKU
from urtils.Mixin import LoginRequiredMixin
from urtils.response_code import RETCODE


class CartsSimpleView(View):
    """商品页面右上角购物车"""

    def get(self, request):
        # 判断用户是否登录
        user = request.user
        if user.is_authenticated():
            # 用户已登录，查询Redis购物车
            redis_conn = get_redis_connection('carts')
            redis_cart = redis_conn.hgetall('carts_%s' % user.id)
            cart_selected = redis_conn.smembers('selected_%s' % user.id)
            # 将redis中的两个数据统一格式，跟cookie中的格式一致，方便统一查询
            cart_dict = {}
            for sku_id, count in redis_cart.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in cart_selected
                }
        else:
            # 用户未登录，查询cookie购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}

        # 构造简单购物车JSON数据
        cart_skus = []
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'default_image_url': settings.FDFS_BASE_URL+sku.default_image
            })

        # 响应json列表数据
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'cart_skus': cart_skus})


class CartsSelectAllView(View):
    """全选购物车"""

    def put(self, request):
        # 接收和校验参数
        # 判断用户是否登录
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected', True)
        user = request.user
        if user is not None and user.is_authenticated():
            # 用户已登录，操作redis购物车
            # 校验参数
            if selected:
                if not isinstance(selected, bool):
                    return http.HttpResponseForbidden('参数selected有误')

            # 连接到redis数据库
            redis_coon = get_redis_connection('carts')
            # 获取所有的记录
            redis_cart = redis_coon.hgetall('carts_%s' % user.id)
            # 管道
            pl = redis_coon.pipeline()
            #  获取所有的字典的kye值
            redis_sku_ids = redis_cart.keys()
            # 判断selected
            if selected:
                # 全选
                pl.sadd("selected_%s" % user.id, *redis_sku_ids)
            else:
                # 取消全选
                pl.srem("selected_%s" % user.id, *redis_sku_ids)
            # 执行
            pl.execute()
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '全选购物车成功'})

        else:
            # 用户未登录，操作cookie购物车
            cart_str = request.COOKIES.get('carts')
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '全选购物车成功'})
            if cart_str:
                # 将cart_str 类型转换为bytes字符串类型
                cart_str_bytes = cart_str.encode()
                # 再转化为bytes字典类型
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                # 再转化为真正的字典类型
                cart_dict = pickle.loads(cart_dict_bytes)

                for sku_id in cart_dict:
                    cart_dict[sku_id]['selected'] = selected
                    # 将真正的字典转为bytes类型的字典
                    cart_dict_bytes = pickle.dumps(cart_dict)
                    # 再将bytes类型的字典转为bytes类型的字符串
                    cart_str_bytes = base64.b64encode(cart_dict_bytes)
                    # 再将bytes类型的字符串转成真正的字符串
                    cookie_cart_str = cart_str_bytes.decode()
                    # 写入到cookie
                    response.set_cookie('carts', cookie_cart_str)
            # 响应结果
            return response


class CartsView(View):
    """购物车管理"""
    def post(self, request):
        # 保存购物车
        # 接收数据
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get("sku_id")
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)  # 可选
        # 校验数据
        # 校验参数是否完整
        if not all([sku_id, count]):
            return http.HttpResponseForbidden("缺少必传参数")
        # 校验sku_id是否合法
        try:
            SKU.objects.get(id=sku_id)
        except ObjectDoesNotExist:
            return http.HttpResponseForbidden("参数sku_id错误")
        # 校验count是否为数字
        try:
            count = int(count)
        except Exception as e:
            return http.HttpResponseForbidden("参数count错误")
        # 校验勾选是否bool
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden("参数selected错误")
        # 验证用户是否登录
        user = request.user
        if user.is_authenticated():
            # 登录用户，操作redis购物车
            redis_coon = get_redis_connection('carts')
            pl = redis_coon.pipeline()

            # 需要以增量计算的保存单位
            pl.hincrby('carts_%s' % user.id, sku_id, count)
            # 保存商品勾选状态
            if selected:
                pl.sadd("selected_%s" % user.id, sku_id)
            # 执行
            pl.execute()

            # 响应结果
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})
        else:
            # 未登录用户，操作cookie购物车
            # 获取购物车的cookie数据，判断是否有数据
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 将cart_str 类型转换为bytes字符串类型
                cart_str_bytes = cart_str.encode()
                # 再转化为bytes字典类型
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                # 再转化为真正的字典类型
                cart_dict = pickle.loads(cart_dict_bytes)
            else:
                # 创建空的字典
                cart_dict = {}

            # 判断当前商品是否再cart_dict存在
            if sku_id in cart_dict:
                # 购物车已存在　增量计算
                origin_count = cart_dict[sku_id]['count']
                count += origin_count

            # 如果cart_dict不存在
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected,
            }
            # 将真正的字典转为bytes类型的字典
            cart_dict_bytes = pickle.dumps(cart_dict)
            # 再将bytes类型的字典转为bytes类型的字符串
            cart_str_bytes = base64.b64encode(cart_dict_bytes)
            # 再将bytes类型的字符串转成真正的字符串
            cookie_cart_str = cart_str_bytes.decode()

            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})
            response.set_cookie('carts', cookie_cart_str)
            # 响应结果
            return response

    def get(self, request):
        """查询购物车"""
        user = request.user
        # 判断用户是否登录
        if user.is_authenticated():
            # 用户已登录查询redis
            # 链接到redis数据库
            redis_coon = get_redis_connection('carts')
            # 取出hash数据
            redis_cart = redis_coon.hgetall('carts_%s' % user.id)
            # 取出set数据
            redis_selected = redis_coon.smembers("selected_%s" % user.id)

            #  将redis_cart和redis_selected进行数据结构的构造，合并数据，数据结构跟未登录数据结构一致
            cart_dict = {}
            for sku_id, count in redis_cart.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in redis_selected,
                }
        else:
            # 未登录查询cookie
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 将cart_str 类型转换为bytes字符串类型
                cart_str_bytes = cart_str.encode()
                # 再转化为bytes字典类型
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                # 再转化为真正的字典类型
                cart_dict = pickle.loads(cart_dict_bytes)
            else:
                # 创建空的字典
                cart_dict = {}

        # 构造响应数据
        sku_ids = cart_dict.keys()
        # for sku_id in sku_ids:
        #     sku = SKU.objects.get(id=sku_id)

        # 一次查询
        skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'selected': str(cart_dict.get(sku.id).get('selected')),  # 将True，转'True'，方便json解析
                'default_image_url': settings.FDFS_BASE_URL+sku.default_image,
                'price': str(sku.price),  # 从Decimal('10.2')中取出'10.2'，方便json解析
                'amount': str(sku.price * cart_dict.get(sku.id).get('count')),
            })

        context = {
            'cart_skus': cart_skus,
        }

        # 渲染购物车页面
        return render(request, 'cart.html', context)

    def put(self, request):
        """修改购物车"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 判断参数是否齐全
        if not all([sku_id, count]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断sku_id是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except ObjectDoesNotExist:
            return http.HttpResponseForbidden('商品sku_id不存在')
        # 判断count是否为数字
        try:
            count = int(count)
        except Exception as e:
            return http.HttpResponseForbidden('参数count有误')
        # 判断selected是否为bool值
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')

        # 判断用户是否登录
        user = request.user
        if user.is_authenticated():
            # 用户已登录，修改redis购物车
            redis_coon = get_redis_connection('carts')
            pl = redis_coon.pipeline()
            # 后端收到的是最终的结果，所以添加
            # pl.hincrby()　使用新值加上旧值(增量)
            pl.hset('carts_%s' % user.id, sku_id, count)
            # 判断是否勾选
            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)
            else:
                pl.srem('selected_%s' % user.id, sku_id)
            # 执行
            pl.execute()

            # 创建响应对象
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'default_image_url': settings.FDFS_BASE_URL+sku.default_image,
                'price': sku.price,
                'amount': sku.price * count,
            }
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})
        else:
            # 用户未登录，修改cookie购物车
            # 获取购物车的cookie数据，判断是否有数据
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 将cart_str 类型转换为bytes字符串类型
                cart_str_bytes = cart_str.encode()
                # 再转化为bytes字典类型
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                # 再转化为真正的字典类型
                cart_dict = pickle.loads(cart_dict_bytes)
            else:
                # 创建空的字典
                cart_dict = {}

            cart_dict[sku_id] = {
                'count': count,
                'selected': selected,
            }

            # 创建响应对象
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'default_image_url': settings.FDFS_BASE_URL+sku.default_image,
                'price': sku.price,
                'amount': sku.price * count,
            }
            # 将真正的字典转为bytes类型的字典
            cart_dict_bytes = pickle.dumps(cart_dict)
            # 再将bytes类型的字典转为bytes类型的字符串
            cart_str_bytes = base64.b64encode(cart_dict_bytes)
            # 再将bytes类型的字符串转成真正的字符串
            cookie_cart_str = cart_str_bytes.decode()

            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'cart_sku': cart_sku})
            response.set_cookie('carts', cookie_cart_str)
            # 响应结果
            return response

    def delete(self, request):
        """删除购物车"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')

        # 判断sku_id是否存在
        try:
            SKU.objects.get(id=sku_id)
        except ObjectDoesNotExist:
            return http.HttpResponseForbidden('商品不存在')

        # 判断用户是否登录
        user = request.user
        if user is not None and user.is_authenticated():
            # 用户已登录，删除redis购物车
            redis_coon = get_redis_connection('carts')
            pl = redis_coon.pipeline()
            # 删除hash购物车记录
            pl.hdel('carts_%s' % user.id, sku_id)
            # 同步移除勾选状态
            pl.srem('selected_%s' % user.id, sku_id)
            # 执行
            pl.execute()
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})
        else:
            # 用户未登录，删除cookie购物车
            # 获取购物车的cookie数据，判断是否有数据
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 将cart_str 类型转换为bytes字符串类型
                cart_str_bytes = cart_str.encode()
                # 再转化为bytes字典类型
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                # 再转化为真正的字典类型
                cart_dict = pickle.loads(cart_dict_bytes)
            else:
                # 创建空的字典
                cart_dict = {}

            # 构造响应对象
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})

            if sku_id in cart_dict:
                del cart_dict[sku_id]   # 如果删除的key不存在，则会抛出异常
                # 将真正的字典转为bytes类型的字典
                cart_dict_bytes = pickle.dumps(cart_dict)
                # 再将bytes类型的字典转为bytes类型的字符串
                cart_str_bytes = base64.b64encode(cart_dict_bytes)
                # 再将bytes类型的字符串转成真正的字符串
                cookie_cart_str = cart_str_bytes.decode()
                # 写入新的cookie
                response.set_cookie('carts', cookie_cart_str)

            return response